package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdminUserService;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;

/**
 * @author JianKang
 * @create 2023-10-29 22:11
 */
@Service
@Transactional
@Slf4j
public class AdminUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdminUserService {
    @Override
    public ResponseResult login(AdUserDto dto) {
        //1.校验参数
        String name = dto.getName();
        String password = dto.getPassword();
        if (StringUtils.isBlank(name) || StringUtils.isBlank(password)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.根据用户名查询用户信息
        AdUser adUser = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, name));
        if (adUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "用户信息不存在");
        }
        String salt = adUser.getSalt();
        //计算加盐密码
        String pswd = DigestUtils.md5DigestAsHex((password + salt).getBytes());
        log.info("加盐：{}", salt);
        log.info("加盐密码：{}", pswd);
        //密码错误
        if (!pswd.equals(adUser.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        String token = AppJwtUtil.getToken(adUser.getId().longValue());
        //对用户隐私信息进行处理
        adUser.setPassword("");
        adUser.setSalt("");
        HashMap<String, Object> map = new HashMap<>();
        map.put("user", adUser);
        map.put("token", token);
        return ResponseResult.okResult(map);
    }
}
